package com.mysoft.gfyx.clue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysoft.framework.common.user.User;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.core.function.authorization.AuthenticationUser;
import com.mysoft.framework.sdk.system.api.SystemDataProvider;
import com.mysoft.framework.sdk.system.dto.UserDTO;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.clue.dao.OpptySubsCustomerDataDao;
import com.mysoft.gfyx.clue.dao.OpptySubsPurchaseDataDao;
import com.mysoft.gfyx.clue.dao.OpptysubsDao;
import com.mysoft.gfyx.clue.dao.entity.OpptySubsCustomerData;
import com.mysoft.gfyx.clue.dao.entity.OpptySubsPurchaseData;
import com.mysoft.gfyx.clue.dao.entity.Opptysubs;
import com.mysoft.gfyx.clue.service.OpptySubsService;
import com.mysoft.gfyx.clue.service.dto.OpptySubsCustomerDataDto;
import com.mysoft.gfyx.clue.service.dto.OpptySubsDto;
import com.mysoft.gfyx.clue.service.dto.OpptySubsPurchaseDataDto;
import com.mysoft.gfyx.clue.service.dto.SubsNameDto;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.sdk.context.core.ThreadContextHolder;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
* 描述：Opptysubs 业务代码
* @author JavaSdk generator
* @date 2022-07-07
*/
@Service

public class OpptySubsServiceImp extends AppService implements OpptySubsService {
    @Resource
    private OpptysubsDao opptysubsDao;

    @Resource
    private OpptySubsCustomerDataDao opptySubsCustomerDataDao;

    @Resource
    private OpptySubsPurchaseDataDao opptySubsPurchaseDataDao;

    @Resource
    private SystemDataProvider systemDataProvider;

    //保存商机订阅
    @Override
    public UUID saveOpptySubs(OpptySubsDto saveOpptySubsDto) {
        //转换对象
        Opptysubs opptysubsEntity = MappingUtil.getSimpleMapperFacade().map(saveOpptySubsDto, Opptysubs.class);
        if (saveOpptySubsDto.getOpptySubsGUID() == null) {
            //判断保存个数
            if (this.getSubsCount() >= OpptySubsService.SUBS_MAXIMUM) {
                throw new BusinessLogicException("订阅个数不能大于"+OpptySubsService.SUBS_MAXIMUM+"个");
            }
            //插入数据表
            opptysubsDao.insert(opptysubsEntity);
        } else {
            opptysubsDao.updateById(opptysubsEntity);
        }

        System.out.println("opptysubsEntity=" + opptysubsEntity);
        return opptysubsEntity.getOpptySubsGUID();
    }

    @Override
    public List<SubsNameDto> getSubsNameList(Integer subsType) {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        QueryWrapper<Opptysubs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SubsType", subsType);
        List<Opptysubs> opptysubsList = opptysubsDao.selectList(queryWrapper);
        System.out.println("opptysubsList=================" + opptysubsList);
        List<SubsNameDto> subsNameList = MappingUtil.getSimpleMapperFacade().mapAsList(opptysubsList, SubsNameDto.class);

        for (SubsNameDto subsNameDto : subsNameList) {
            Long subsCount = 0L;
            // 枚举。0企业潜在机会；1采购公告信息
            if (subsNameDto.getSubsType() == 0) {
                QueryWrapper<OpptySubsCustomerData> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("CreatedGUID", authenticationUser.getUserId());
                subsCount = opptySubsCustomerDataDao.selectCount(queryWrapper2);
            } else {
                QueryWrapper<OpptySubsPurchaseData> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("CreatedGUID", authenticationUser.getUserId());
                subsCount = opptySubsPurchaseDataDao.selectCount(queryWrapper2);
            }
            subsNameDto.setSubCount(Math.toIntExact(subsCount));
            subsNameDto.setSubsNameCountText(subsNameDto.getSubsName() + "("+subsNameDto.getSubCount()+")");
        }
        System.out.println("subsNameList=================" + subsNameList);
        return subsNameList;
    }

    @Override
    public int getSubsCount() {
        User authenticationUser = ThreadContextHolder.getInstance().get(AuthenticationUser.class);
        QueryWrapper<Opptysubs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CreatedGUID", authenticationUser.getUserId());
        return Math.toIntExact(opptysubsDao.selectCount(queryWrapper));
    }

    public boolean enable(UUID opptySubsGUID, int enable) {
        Opptysubs opptysubs = new Opptysubs();
        opptysubs.setOpptySubsGUID(opptySubsGUID);
        opptysubs.setEnable(enable);
        if (enable == 0) {
            opptysubs.setEnableText("已停用");
        } else if (enable == 1) {
            opptysubs.setEnableText("已启用");
        }
        opptysubsDao.updateById(opptysubs);
        return true;
    }

    /**
     * 删除商机订阅
     * @param opptySubsGUID
     * @return
     */
    public boolean delete(UUID opptySubsGUID) throws BusinessLogicException {
        Opptysubs opptysubs =  opptysubsDao.selectById(opptySubsGUID);
        if (opptysubs == null) {
            throw new BusinessLogicException("商机订阅记录不存在");
        }
        opptysubsDao.deleteById(opptysubs);
        return true;
    }

    @Override
    public OpptySubsDto getOne(UUID opptySubsGUID) throws BusinessLogicException {
        Opptysubs opptysubs = opptysubsDao.selectById(opptySubsGUID);
        if (opptysubs == null) {
            return null;
        }
        OpptySubsDto opptysubsDto = MappingUtil.getSimpleMapperFacade().map(opptysubs, OpptySubsDto.class);
        String[] pushUserList = opptysubsDto.getPushUserList().split(",");
        List<String> pushUserNameList = new ArrayList<>();
        for (String pushUserGuid : pushUserList) {
            String userName = "";
            try {
                UserDTO user = systemDataProvider.getUser(pushUserGuid);
                System.out.println("user========"+ user + "pushUserGuid==" + pushUserGuid);
                System.out.println(" pushUserGuid==" + pushUserGuid);
                userName = user != null ? user.getUserName() : "";
            } catch (Exception e) {
                userName = "";
            }
            pushUserNameList.add(userName);
        }
        opptysubsDto.setPushUserNameList(StringUtil.join(",", pushUserNameList.toArray()));

//        String[] pushWaySplit = opptysubsDto.getPushWay().split(",");
//        List<String> pushWayTextList = new ArrayList<>();
//        for (String pushWay : pushWaySplit) {
//            if (pushWay.equals("0")) {
//                pushWayTextList.add("微信公众号");
//            } else if (pushWay.equals("1")) {
//                pushWayTextList.add("短信");
//            }
//        }
//        opptysubsDto.setPushWayText(StringUtil.join(",", pushWayTextList.toArray()));
//
//        if (opptysubsDto.getEnable() == 1) {
//            opptysubsDto.setEnableText("已启用");
//        } else if (opptysubsDto.getEnable() == 0) {
//            opptysubsDto.setEnableText("已停用");
//        }
//
//        if (opptysubsDto.getSubsType() == 0) {
//            opptysubsDto.setSubsTypeText("企业");
//        } else if (opptysubsDto.getSubsType() == 1) {
//            opptysubsDto.setSubsTypeText("采购");
//        }
        return opptysubsDto;
    }

    @Override
    public List<OpptySubsDto> getAllEnabledOpptySubs() throws BusinessLogicException {
        QueryWrapper<Opptysubs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Enable", 1);
        queryWrapper.last("limit 2000");
        List<Opptysubs> opptysubsList = opptysubsDao.selectList(queryWrapper);
        return MappingUtil.getSimpleMapperFacade().mapAsList(opptysubsList, OpptySubsDto.class);
    }

    @Override
    public List<OpptySubsDto> getAllEnabledAndNextPushTimeIsNullOpptySubs(UUID opptySubsGUID) throws BusinessLogicException {
        QueryWrapper<Opptysubs> queryWrapper = new QueryWrapper<>();

        if (opptySubsGUID != null) {
            queryWrapper.eq("opptySubsGUID", opptySubsGUID);
        } else {
            queryWrapper.eq("Enable", 1);
            queryWrapper.isNull("NextPushTime");
            queryWrapper.last("limit 2000");
        }
        List<Opptysubs> opptysubsList = opptysubsDao.selectList(queryWrapper);
        return MappingUtil.getSimpleMapperFacade().mapAsList(opptysubsList, OpptySubsDto.class);
    }

    //获取一分钟内推送的订阅
    @Override
    public List<OpptySubsDto> getAllInOneMinuteEnabledOpptySubs() throws BusinessLogicException {
        List<Opptysubs> opptysubsList = opptysubsDao.getAllInOneMinuteEnabledOpptySubs();
        return MappingUtil.getSimpleMapperFacade().mapAsList(opptysubsList, OpptySubsDto.class);
    }

    @Override
    public UUID saveOpptySubsCustomerData(OpptySubsCustomerDataDto opptySubsCustomerDataDto) {
        //转换对象
        OpptySubsCustomerData opptySubsCustomerData = MappingUtil.getSimpleMapperFacade().map(opptySubsCustomerDataDto, OpptySubsCustomerData.class);
        if (opptySubsCustomerData == null) {
            return null;
        }
        //插入数据表
        opptySubsCustomerDataDao.insert(opptySubsCustomerData);
        System.out.println("opptySubsCustomerData=" + opptySubsCustomerData);
        return opptySubsCustomerData.getOpptySubsCustomerDataGUID();
    }

    @Override
    public UUID saveOpptySubsPurchaseData(OpptySubsPurchaseDataDto opptySubsPurchaseDataDto) {
        //转换对象
        OpptySubsPurchaseData opptySubsPurchaseData = MappingUtil.getSimpleMapperFacade().map(opptySubsPurchaseDataDto, OpptySubsPurchaseData.class);
        if (opptySubsPurchaseData == null) {
            return null;
        }
        //插入数据表
        opptySubsPurchaseDataDao.insert(opptySubsPurchaseData);
        System.out.println("opptySubsPurchaseDataDao=" + opptySubsPurchaseData);
        return opptySubsPurchaseData.getOpptySubsPurchaseDataGUID();
    }
}
